﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApiClientCore;
using WebApiClientCore.Attributes;

namespace Ongoal.Quotation.Attributes.NetCoreClient
{
    public class ServiceHostByServiceNameAttribute : ApiActionAttribute
    {
        private const string _serviceHostKey = "serviceHost";
        public ServiceHostByServiceNameAttribute()
        {
        }

        public string Name { get; set; }

        public override async Task OnRequestAsync(ApiRequestContext context)
        {
            string host;
            if (!context.TryGetArgument(_serviceHostKey, out host) && host == null)
            {
                throw new ArgumentException($"接口调用检测异常，无法找到{_serviceHostKey}参数");
            }
            HttpApiRequestMessage requestMessage = context.HttpContext.RequestMessage;
            // 覆盖了RequestUri,完成了替换
            requestMessage.RequestUri = requestMessage.MakeRequestUri(new Uri(host));

            await Task.CompletedTask;
        }
    }

}
